<?php

defined('ROOT') or die('No direct script access.');
class CMain extends CController
{
    public function action_index()
    {
        $model = new MLog();
        $rows = $model->fetch_all("select * from ##_users");
        print_r($rows);
        $widgets = new CWidgets();
        $prm_data = array(
            'widget_login' => $widgets->widget_login(),
        );
        $view = new CView();
        $view->assign($prm_data);
        $view->display("index");
    }
    
    public function action_sqlite($params){
        $data = new MTable();
        $rows = $data->fetch_all('SELECT * FROM messages');
        //print_r($rows);
        foreach($rows as $row){
            echo ''.$row->author.': '.$row->chatname.': '.$row->body_xml.'<br>';
            }
        
    }

    public function action_list($param)
    {
        $m_users = new MUsers;
        $data = $m_users->get_list();
        $arr_exclude = array('pw');
        //! Добавляем возможные действия со списком
        //! act - название метода в контроллере (без action_)
        $ar_acts = array(array('controller' => 'users', 'acts' => array('add', 'edit', 'del')));
        $prm_data = array(
            'params'      => $params,
            'table_data'  => $data,
            'arr_exclude' => $arr_exclude,
            'ar_acts'     => $ar_acts,
        );
        $view = new CView();
        $view->assign($prm_data);
        $view->display("table");
    }

    public function action_edit($params)
    {
        $m_users = new MUsers;
        $data = $m_users->get_by_id((int)$params['id']);
        $arr_cols = array(
            array('name' => 'id', 'type' => 'edit', 'title' => 'ID', 'disabled' => 1),
            array('name' => 'login', 'type' => 'edit', 'title' => 'Логин'),
            array('name' => 'pw', 'type' => 'edit', 'title' => 'Пароль'),
        );
        $prm_data = array(
            'data'     => $data,
            'params'   => $params,
            'arr_cols' => $arr_cols,
            //! Прописываем обработчик формы
            //! act - название метода в контроллере (без action_)
            //'controller' => array('name' => "users", 'act' => 'save'),
        );
        $view = new CView();
        $view->assign($prm_data);
        $view->display("row");
    }

    public function action_codegen()
    {
        $view = new CView();
        //$view->assign($prm_data);
        $view->display("frm_codegen.php");
    }

    public function action_tableinfo()
    {
        $frm_data = self::escape_array($_POST);
        $arr_db_config = array(
            'connection_string' => $frm_data['connection_string'],
            'user_name'         => $frm_data['login'],
            'password'          => $frm_data['password'],
            'dbprefix'          => $frm_data['db_prefix'],
            'encoding'          => 'utf8',
        );
        $db_con = new CDBConnection($arr_db_config);
        $model = new MTable($db_con);
        $arr_cools = $model->fetch_all("SHOW COLUMNS FROM ##_" . $frm_data['table_name']);
        //print_r($arr_cools);
        $lst_types = array(
            array('id'=> 'edit', 'title'=> 'edit'),
            array('id'=> 'select', 'title'=> 'select'),
            array('id'=> 'multiple', 'title'=> 'multiple'),
            array('id'=> 'text', 'title'=> 'text'),
            array('id'=> 'checkbox', 'title'=> 'checkbox'),
            array('id'=> 'hidden', 'title'=> 'hidden'),
            array('id'=> '-', 'title'=> 'Не выводить'),
        );
        $prm_data = array(
            'rows'               => $arr_cools,
            'lst_frm_types'      => $lst_types,
            'table_name'         => $frm_data['table_name'],
            'template_folder'    => $frm_data['template_folder'],
            'app_path'           => $frm_data['app_path'],
        );
        $view = new CView();
        $view->assign($prm_data);
        $view->display("frm_db_collumns.php");
    }

    public function parse_template($params)
    {
        
        $template_name = $params['template_name'];
        $template_folder = $params['template_folder'];
        $folder_name = $params['folder_name'];
        $obj_name = $params['obj_name'];
        $app_path = $params['app_path'];
        $arr_template_names = $params['arr_template_names'];
        $arr_value_names = $params['arr_value_names'];
        $file = 'application/templates/' . trim($template_folder) . '/' . $template_name . '.php';
        $newfile = strtolower($app_path . "/" . $folder_name . "/" . $obj_name . '.php');
        
        echo $newfile."<br>";
        
        if (file_exists($newfile))
        {
            unlink($newfile);
            echo 'Удален файл: '.$newfile."<br>";
        }
        
        if (!copy($file, $newfile)) {
            echo "не удалось создать файл: $file...\n";
            return false;
        } else {
            $str_file = file_get_contents($newfile);
            $newphrase = str_replace($arr_template_names, $arr_value_names, $str_file);
            file_put_contents($newfile, $newphrase);
            //echo "Создан файл: $file...\n";
            return false;
        }
    }

    public function action_genform()
    {
        $frm_data = self::escape_array($_POST);
        
        $manager_model_name = $frm_data['manager_model_name'];
        $record_model_name = $frm_data['record_model_name'];
        $controller_name = $frm_data["controller_name"];
        $view_form_name = strtolower($frm_data['rec_view_form_name']);
        $list_form_name = strtolower($frm_data['list_form_name']);
        $table_name = $frm_data['table_name'];
        $form_name = strtolower($frm_data['rec_form_name']);
        $rec_name = $frm_data['rec_name'];
        //
        $template_folder = $frm_data['template_folder'];
        $app_path = $frm_data['app_path'];
        //
        $controller_path = strtolower($controller_name);
        $str_vars = "";
        $str_methods = "";
        $form_content = "";
        //
        $arr_from = array("{TemplateRecordName}", "{TemplateManagerName}", "{TemplateControllerName}", "{TemplateControllerPath}", "{TemplateFormName}", "{TemplateFormViewName}", "{TemplateListName}", "{TemplateFormRecordName}", "{TemplateClassVars}", "{TemplateClassMethods}", "{TemplateTableName}", "{TemplateFormContent}",);
        //
        if ($frm_data['cbox_controller'] == 'on') {
            $params = array();
            $params['folder_name'] = "controllers";
            $params['template_name'] = "controller";
            $params['obj_name'] = "c" . $controller_name;
            $params['app_path'] = $app_path;
            $params['template_folder'] = $template_folder;
            $arr_to = array($record_model_name, $manager_model_name, $controller_name, $controller_path, $form_name, $view_form_name, $list_form_name, $rec_name, $str_vars, $str_methods, $table_name, $form_content,); //
            $params['arr_template_names'] = $arr_from;
            $params['arr_value_names'] = $arr_to;
            self::parse_template($params);
        }
        if ($frm_data['cbox_rec_model'] == 'on') {
            $str_vars = '';
            $str_vars_for_save = "\r\n\$data = array();\r\n";
            $str_methods = "";
            $str_set_vals = 'public function set_form_values($params) {' . "\r\n";
            $str_set_vals .= '   $post = self::escape($params["post"]);';
            foreach (array_keys($frm_data) as $key) {
                if (!strpos($key, '_frm_control')) {
                    continue;
                }
                $field_name = str_replace('_frm_control', '', $key);
                $type_input = $frm_data[$key];
                $str_vars .= "public $" . $field_name . ";\r\n";
                $str_vars_for_save .= "\$data['$field_name'] = \$this->$field_name;\r\n";
                $function_name = $frm_data[$field_name . "_function"];
                $link_model = $frm_data[$field_name . "_link"];
                if ($function_name != "") {
                    $str_methods .= "public function " . $function_name . "() {\r\n";
                    $str_methods .= "   $" . "model = new " . $link_model . "();\r\n";
                    $str_methods .= "   return $" . "model->get_by_id($" . "this->" . $field_name . ");\r\n";
                    $str_methods .= "}\r\n";
                }
                if ($type_input != "-") {
                    if ($type_input == "checkbox") {
                        $str_set_vals .= '  $this->' . $field_name . ' = (($post["' . $field_name . '"] == "on") ? 1: 0);' . "\r\n";
                    } else {
                        $str_set_vals .= '  $this->' . $field_name . ' = $post["' . $field_name . '"];' . "\r\n";
                    }
                }
            }
            $str_set_vals .= '}' . "\r\n";
            $str_set_vals .= 'public function save() { ' . $str_vars_for_save . '$this->id = self::save_to("##_' . $table_name . '", $data);'."\r\n".' return $this->id; }' . "\r\n";
            $str_methods .= $str_set_vals;
            $params = array();
            $params['folder_name'] = "models";
            $params['template_name'] = "model";
            $params['obj_name'] = $record_model_name;
            $params['app_path'] = $app_path;
            $params['template_folder'] = $template_folder;
            $arr_to = array($record_model_name, $manager_model_name, $controller_name, $controller_path, $form_name, $view_form_name, $list_form_name, $rec_name, $str_vars, $str_methods, $table_name, $form_content,); //
            $params['arr_template_names'] = $arr_from;
            $params['arr_value_names'] = $arr_to;
            self::parse_template($params);
        }
        if ($frm_data['cbox_manager_model'] == 'on') {
            $params = array();
            $params['folder_name'] = "models";
            $params['template_name'] = "model_manager";
            $params['obj_name'] = $manager_model_name;
            $params['app_path'] = $app_path;
            $params['template_folder'] = $template_folder;
            $arr_to = array($record_model_name, $manager_model_name, $controller_name, $controller_path, $form_name, $view_form_name, $list_form_name, $rec_name, $str_vars, $str_methods, $table_name, $form_content,); //
            $params['arr_template_names'] = $arr_from;
            $params['arr_value_names'] = $arr_to;
            self::parse_template($params);
        }
        if ($frm_data['cbox_rec_frm'] == 'on') {
            $hidden = "";
            $str = "<form action='/" . strtolower($controller_path) . "/save' method=post>";
            $str .= "<table>";
            foreach (array_keys($frm_data) as $key) {
                $type_input = $frm_data[$key];
                //            echo $key;
                if (!strpos($key, '_frm_control')) {
                    continue;
                }
                $field_name = str_replace('_frm_control', '', $key);
                if ($type_input == "-") {
                    continue;
                }
                if ($type_input == "hidden") {
                    $hidden .= "<input type='hidden' name='$field_name' id='$field_name' value='<?php echo $" . $rec_name . "->$field_name; ?>' >";
                    continue;
                }
                if ($type_input == "checkbox") {
                    $str .= "<tr>";
                    $str .= "<td>&nbsp;";
                    $str .= "</td>";
                    $str .= "<td>";
                    if (substr($frm_data[$field_name . "_lbl"], 0, 1) == ":") {
                        $lbl .= substr($frm_data[$field_name . "_lbl"], 1);
                    } else {
                        if ($frm_data[$field_name . "_lbl"] != "") {
                            $lbl .= "'" . $frm_data[$field_name . "_lbl"] . "'";
                        } else {
                            $lbl .= "'" . $field_name . "'";
                        }
                    }
                    $str .= "<?php echo form_checkbox($lbl,'$field_name',$" . $rec_name . "->$field_name); ?>";
                    $str .= "</td>";
                    $str .= "</tr>";
                    continue;
                }
                $list = $frm_data[$field_name . "_list"];
                $str .= "<tr>";
                $str .= "<td>";
                $lbl = "";
                if (substr($frm_data[$field_name . "_lbl"], 0, 1) == ":") {
                    $str .= "<?php echo " . substr($frm_data[$field_name . "_lbl"], 1) . "; ?>";
                } else {
                    if ($frm_data[$field_name . "_lbl"] != "") {
                        $str .= "'" . $frm_data[$field_name . "_lbl"] . "'";
                    } else {
                        $str .= $field_name;
                    }
                }
                $str .= "</td>";
                $str .= "<td>";
                if ($type_input == "select") {
                    $str .= "<?php echo form_combo('$field_name', $" . $rec_name . "->$field_name, $list); ?>";
                }
                if ($type_input == "multiple") {
                    $str .= "<?php echo form_combo_multiple('$field_name', $" . $rec_name . "->$field_name, $list); ?>";
                }
                if ($type_input == "edit") {
                    $str .= "<?php echo form_edit('$field_name',50, $" . $rec_name . "->$field_name); ?>";
                }
                if ($type_input == "text") {
                    $str .= "<?php echo form_text('$field_name',5,10, $" . $rec_name . "->$field_name); ?>";
                }
                $str .= "</td>";
                $str .= "</tr>";
            }
            $str .= "</table>";
            $str .= "<button type=submit class=btn>Сохранить</button>";
            $str .= $hidden;
            $str .= "</form>";
            $form_content = $str;
            $params = array();
            $params['folder_name'] = "views";
            $params['template_name'] = "form_edit";
            $params['obj_name'] = $form_name;
            $params['app_path'] = $app_path;
            $params['template_folder'] = $template_folder;
            $arr_to = array($record_model_name, $manager_model_name, $controller_name, $controller_path, $form_name, $view_form_name, $list_form_name, $rec_name, $str_vars, $str_methods, $table_name, $form_content,); //
            $params['arr_template_names'] = $arr_from;
            $params['arr_value_names'] = $arr_to;
            self::parse_template($params);
        }
        if ($frm_data['cbox_rec_view_frm'] == 'on') {
            $hidden = "";
            $str = "<table>";
            foreach (array_keys($frm_data) as $key) {
                $type_input = $frm_data[$key];
                if (!strpos($key, '_frm_control')) {
                    continue;
                }
                $field_name = str_replace('_frm_control', '', $key);
                if ($type_input == "-") {
                    continue;
                }
                if ($type_input == "checkbox") {
                    $str .= "<tr>";
                    $str .= "<td>&nbsp;";
                    $str .= "</td>";
                    $str .= "<td>";
                    if (substr($frm_data[$field_name . "_lbl"], 0, 1) == ":") {
                        $lbl .= substr($frm_data[$field_name . "_lbl"], 1);
                    } else {
                        if ($frm_data[$field_name . "_lbl"] != "") {
                            $lbl .= "'" . $frm_data[$field_name . "_lbl"] . "'";
                        } else {
                            $lbl .= "'" . $field_name . "'";
                        }
                    }
                    $str .= "<?php echo form_checkbox($lbl,'$key',$" . $rec_name . "->$field_name,'',1); ?>";
                    $str .= "</td>";
                    $str .= "</tr>";
                    continue;
                }
                $function_name = $frm_data[$field_name . "_function"];
                $str .= "<tr>";
                $str .= "<td>";
                $lbl = "";
                if (substr($frm_data[$field_name . "_lbl"], 0, 1) == ":") {
                    $str .= "<?php echo " . substr($frm_data[$field_name . "_lbl"], 1) . "; ?>";
                } else {
                    if ($frm_data[$field_name . "_lbl"] != "") {
                        $str .= "'" . $frm_data[$field_name . "_lbl"] . "'";
                    } else {
                        $str .= $field_name;
                    }
                }
                $str .= "</td>";
                $str .= "<td>";
                if ($type_input == "select") {
                    $str .= '<?php echo $' . $rec_name . '->' . $function_name . '()->title; ?>';
                }
                if ($type_input == "multiple") {
                    $str .= "<?php echo form_combo_multiple('$field_name', $" . $rec_name . "->$field_name, $list,5,'',1); ?>";
                }
                if ($type_input == "edit") {
                    $str .= "<?php echo $" . $rec_name . "->$field_name; ?>";
                }
                if ($type_input == "text") {
                    $str .= "<?php echo nl2br($" . $rec_name . "->$field_name); ?>";
                }
                $str .= "</td>";
                $str .= "</tr>";
            }
            $str .= "</table>";
            $str .= $hidden;
            $form_content = $str;
            $params = array();
            $params['folder_name'] = "views";
            $params['template_name'] = "form_edit";
            $params['obj_name'] = $view_form_name;
            $params['app_path'] = $app_path;
            $params['template_folder'] = $template_folder;
            $arr_to = array($record_model_name, $manager_model_name, $controller_name, $controller_path, $form_name, $view_form_name, $list_form_name, $rec_name, $str_vars, $str_methods, $table_name, $form_content,); //
            $params['arr_template_names'] = $arr_from;
            $params['arr_value_names'] = $arr_to;
            self::parse_template($params);
        }
        if ($frm_data['cbox_list_frm'] == 'on') {
            $params = array();
            $params['folder_name'] = "views";
            $params['template_name'] = "list";
            $params['obj_name'] = $list_form_name;
            $params['app_path'] = $app_path;
            $params['template_folder'] = $template_folder;
            $arr_to = array($record_model_name, $manager_model_name, $controller_name, $controller_path, $form_name, $view_form_name, $list_form_name, $rec_name, $str_vars, $str_methods, $table_name, $form_content,); //
            $params['arr_template_names'] = $arr_from;
            $params['arr_value_names'] = $arr_to;
            self::parse_template($params);
        }
    }
}